﻿using Inovout.Cloud.Applications.Models;
using Inovout.Cloud.Applications.Security.Models;
using Inovout.Cloud.Applications.Security.Services;
using Inovout.Cloud.Models;
using Inovout.Cloud.Services;
using Inovout.Cloud.Storage.Web.Models;
using Inovout.Cloud.Web.Http;
using Inovout.Organizations.Memberships.Models;
using Inovout.Organizations.Memberships.Services;
using Inovout.Organizations.Models;
using Inovout.Security;

namespace Inovout.Cloud.Storage.Web.Controllers
{
    public class ProjectController : CloudHttpController
    {
        public void Activate(ProjectObject project)
        {
            IOrganizationMembershipService organizationMembershipService = ComponentRegistry.Resolve<IOrganizationMembershipService>();
            OrganizationMembership organizationMembership = organizationMembershipService.FindByUserName(project.org_username);
            if (organizationMembership == null)
            {
                FormsUserCredential ownerUser = new FormsUserCredential
                {
                    UserName = project.org_username,
                    Password = "123456"
                };
                organizationMembership = organizationMembershipService.Create(
                     new OrganizationUnit { Name = project.org_name },
                     ownerUser, Memberships.MembershipUserStatus.Inactivate
                     ).Membership as OrganizationMembership;
            }
            IApplicationUserService applicationUserService = ComponentRegistry.Resolve<IApplicationUserService>();
            ApplicationUser applicationUser = applicationUserService.FindByName(project.app_key);
            if (applicationUser == null)
            {
                applicationUser = new ApplicationUser
            {
                Name = project.app_key,
                Application = new Application
                {
                    Name = project.app_key,
                    Membership = organizationMembership
                }
            };
                applicationUserService.Save(applicationUser);
            }

            IProjectService projectService = ComponentRegistry.Resolve<IProjectService>();
            projectService.Save(new Project
            {
                Name = project.proj_name,
                Title = project.proj_title
            });

        }
    }
}